package scatter.dataconstraint.rest.config;

import cn.hutool.core.annotation.AnnotationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import scatter.common.boot.OnApplicationRunnerListener;
import scatter.common.rest.dataconstraint.DataConstraint;
import scatter.dataconstraint.pojo.po.DataObject;
import scatter.dataconstraint.rest.service.IDataObjectService;

import java.util.Map;

/**
 * 数据对象初始化
 * Created by yangwei
 * Created at 2021/4/1 10:31
 */
@Component
public class DataObjectInitApplicationRunnerListener implements OnApplicationRunnerListener {
    @Autowired
    private RequestMappingHandlerMapping handlerMapping;
    @Autowired
    private IDataObjectService iDataObjectService;
    @Override
    public void run(ApplicationArguments args) throws Exception {

        Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> requestMappingInfoHandlerMethodEntry : handlerMethods.entrySet()) {
            HandlerMethod value = requestMappingInfoHandlerMethodEntry.getValue();
            DataConstraint annotation = AnnotationUtil.getAnnotation(value.getMethod(), DataConstraint.class);
            if (annotation == null){
                annotation = AnnotationUtil.getAnnotation(value.getBeanType(), DataConstraint.class);
            }
            if (annotation != null && !annotation.ignore()) {
                saveByAnnotation(annotation);
            }
        }
    }

    private void saveByAnnotation(DataConstraint dataConstraint) {
        DataObject dataObject = new DataObject();
        dataObject.setCode(dataConstraint.doc());
        dataObject.setName(dataConstraint.name());
        dataObject.setRemark(dataConstraint.remark());
        dataObject.setIsDataLazy(false);
        DataObject byCode = iDataObjectService.getByCode(dataConstraint.doc());
        if (byCode == null) {
            iDataObjectService.save(dataObject);
        }
    }
}
